package cjyyp.netty中黏包半包问题;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * 1. 短链接，发一个包建立一次连接，这样连接建立到连接断开之间就是消息的边界，缺点效率太低
 * 2. 每一条消息采用固定长度，缺点浪费空间
 * 3. 每一条消息采用分隔符，例如 \n，缺点需要转义
 * 4. 每一条消息分为 head 和 body，head 中包含 body 的长度
 */
@Slf4j
public class 服务端 {
    public static void main(String[] args) {
        DefaultEventLoop eventLoop = new DefaultEventLoop();
        ChannelFuture channelFuture = new ServerBootstrap()
                //参数1：只负责ServerSocketChannel的accept事件。参数2：只负责SocketChannel的读写事件
                .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //todo 处理netty中黏包半包问题
                        //todo 最大长度，长度偏移，长度占用字节，长度调整，剥离字节数 ！！！
                        ch.pipeline().addLast(eventLoop, "黏包半包问题处理", new LengthFieldBasedFrameDecoder(1024, 0, 1, 0, 1));
                        //eventLoop参数，是让eventLoop负责的线程专门来处理回调函数
                        ch.pipeline().addLast(eventLoop, "handler-1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.info("handler-1处理消息[{}]", byteBuf.toString(StandardCharsets.UTF_8));
                                ctx.fireChannelRead(msg);//todo 让消息传递给下一个handler
                            }
                            //不写默认让EventLoopGroup来处理回调函数
                        });
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                Channel channel = ctx.channel();
                                ByteBuf response = ctx.alloc().buffer(30);
                                response.writeBytes(byteBuf);
                                log.info("handler-2回写消息[{}]", response.toString(StandardCharsets.UTF_8));
                                channel.writeAndFlush(response);//todo 这里的object参数一定是ByteBuf对象！！！
                                super.channelRead(ctx, msg);//相当于 ctx.fireChannelRead(msg);
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
